package org.ruoyi.interview.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.ruoyi.interview.config.Ultra;
import org.ruoyi.interview.config.XunfeiSparkConfig;
import org.ruoyi.interview.service.IInterviewAIService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.beans.factory.InitializingBean;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 讯飞星火API服务实现类
 */
@Slf4j
@Service
public class XunfeiSparkServiceImpl implements IInterviewAIService, InitializingBean {
    
    @Autowired
    private XunfeiSparkConfig xunfeiSparkConfig;
    private Ultra ultraClient;
    
    // 存储用户会话历史
    private Map<Long, List<Ultra.RoleContent>> userHistories = new ConcurrentHashMap<>();
    
    @Override
    public void afterPropertiesSet() throws Exception {
        ultraClient = new Ultra();
        ultraClient.setApiKey(xunfeiSparkConfig.getApiKey());
        ultraClient.setApiSecret(xunfeiSparkConfig.getApiSecret());
        ultraClient.setAppId(xunfeiSparkConfig.getAppId());
    }
    
    /**
     * 调用讯飞星火大模型API回答问题
     *
     * @param question 用户问题
     * @return 模型回答
     * @throws Exception 调用异常
     */
    @Override
    public String askModel(String question) throws Exception {
        return askModel(question, 0L); // 默认用户ID为0
    }
    
    /**
     * 调用讯飞星火大模型API回答问题（带用户ID）
     *
     * @param question 用户问题
     * @param userId   用户ID
     * @return 模型回答
     * @throws Exception 调用异常
     */
    public String askModel(String question, Long userId) throws Exception {
        try {
            log.info("调用讯飞星火API，用户ID：{}，问题：{}", userId, question);
            
            // 获取用户历史对话记录
            List<Ultra.RoleContent> history = userHistories.computeIfAbsent(userId, k -> new ArrayList<>());
            
            // 调用API
            String response = ultraClient.chat(question, history);
            
            log.info("讯飞星火API返回结果：{}", response);
            
            return response;
        } catch (Exception e) {
            log.error("调用讯飞星火API失败，用户ID：{}，问题：{}", userId, question, e);
            throw new Exception("调用AI服务失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 清除用户历史对话记录
     *
     * @param userId 用户ID
     */
    public void clearHistory(Long userId) {
        userHistories.remove(userId);
    }
}